﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ComLib.Lang.Runtime.Switches;

namespace Fluentscript.Exe.Lib.Switches
{
    public class PublishSwitch : Switch
    {
        private string _scriptsFolder;
        private string _publishPath;


        /// <summary>
        /// Initialize with the metadata switch.
        /// </summary>
        /// <param name="scriptsFolder"></param>
        public PublishSwitch(string scriptsFolder, string publishPath)
        {
            _scriptsFolder = scriptsFolder;
            _publishPath = publishPath;
        }


        /// <summary>
        /// Generates the xml metadata for each script.
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public override object DoExecute(ComLib.Lang.Interpreter i)
        {
            if (!Directory.Exists(_scriptsFolder))
                throw new DirectoryNotFoundException("Directory for plugins : " + _scriptsFolder + " does not exist");

            var files = Directory.GetFiles(_scriptsFolder);
            
            foreach (var file in files)
            {
                var content = File.ReadAllText(file);
                var fileInfo = new FileInfo(file);
                var finalContent = Extract(fileInfo.Name, content);
                var prodPath = Path.Combine(_publishPath, fileInfo.Name);
                File.WriteAllText(prodPath, finalContent);
                Console.WriteLine("Created production version of : " + fileInfo.Name);
            }
            return null;
        }


        /// <summary>
        /// Extract the metadata section from the content
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private static string Extract(string fileName, string content)
        {
            var buffer = new StringBuilder();
            var directiveStart = "@if";
            var directiveEnd = "@endif";

            var ndxIf = content.IndexOf(directiveStart);
            var startPos = 0;
            var hasAnyDirectives = false;
            var ndxEndIf = 0;

            while(ndxIf > 0)
            {
                hasAnyDirectives = true;

                // 1. Get the text up to the @if
                var length = ndxIf - startPos;
                var text = content.Substring(startPos, length);
                buffer.Append(text);

                // 2. Now get next position of @endif
                ndxEndIf = content.IndexOf(directiveEnd, ndxIf);

                // Error condition
                if(ndxEndIf < 0 )
                    throw new ArgumentException("Missing @endif directive in file: " + fileName + ", for @if at pos: " + ndxIf);

                // 3. Reset the start pos
                startPos = ndxEndIf + 6;

                // 4. Get the ndxIf position.
                ndxIf = content.IndexOf(directiveStart, startPos);
            }
            if(hasAnyDirectives && startPos < content.Length - 1)
            {
                var remaining = content.Substring(startPos);
                buffer.Append(remaining);
            }
            if ( !hasAnyDirectives)
                buffer.Append(content);

            return buffer.ToString();
        }
    }
}
